# @Time  :2021/3/30 14:14
# @Author: Houtaroy
import pytest
import os
import tempfile

from flask import Flask

from flask_koala import Koala
from flask_koala.core.database import db as koala_db
from flask_koala.core.domain import Entity, AuditEntity
from flask_koala.system.models import User, UserDTO, Role, RoleDTO, Permission, PermissionDTO, Api


class Visitor(Entity):
    name = koala_db.Column(koala_db.String(200), nullable=False)


class AuditVisitor(AuditEntity):
    name = koala_db.Column(koala_db.String(200), nullable=False)


apis = [
    {'code': 'api:auth:info', 'name': 'api01', 'url': '/api/01', 'method': 'get'},
    {'code': 'api:auth:permissions', 'name': 'api02', 'url': '/api/02', 'method': 'post'},
    {'code': 'api:users:page', 'name': '用户分页查询', 'url': '/api/users', 'method': 'get'},
    {'code': 'api:users:create', 'name': '创建', 'url': '/api/users', 'method': 'post'},
    {'code': 'api:users:load', 'name': '查看', 'url': '/api/users/<int:id>', 'method': 'get'},
    {'code': 'api:users:update', 'name': '查看', 'url': '/api/users/<int:id>', 'method': 'put'},
    {'code': 'api:users:delete', 'name': '查看', 'url': '/api/users/<int:id>', 'method': 'delete'}
]

permissions = [
    {'code': 'admin', 'name': '系统管理员权限'},
]

roles = [
    {'code': 'admin', 'name': '系统管理员角色'}
]

user = {'username': 'admin', 'password': '123456', 'name': '系统管理员', 'gender': 1}


def init_data():
    koala_db.create_all()
    for api in apis:
        Api.add(api)
    for permission in permissions:
        Permission.add(permission)
    for role in roles:
        Role.add(role)
    User.add(user)
    permission_admin = PermissionDTO.get(1)
    permission_admin.apis = Api.search()
    role_admin = RoleDTO.get(1)
    role_admin.permissions.append(permission_admin)
    user_admin = UserDTO.get(1)
    user_admin.roles.append(role_admin)
    koala_db.session.commit()


@pytest.fixture(scope="session")
def app():
    app = Flask(__name__)
    db_fd, db_file_path = tempfile.mkstemp(".db", dir="")
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % db_file_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config["JWT_SECRET_KEY"] = "Houtaroy"
    app.config['TESTING'] = True
    try:
        Koala(app)
        with app.test_request_context():
            yield app
    finally:
        os.close(db_fd)
        os.unlink(db_file_path)


@pytest.fixture(scope="session")
def db():
    init_data()
    try:
        yield koala_db
    finally:
        koala_db.close_all_sessions()
        koala_db.drop_all()


@pytest.fixture(scope='session')
def client(app, db):
    with app.test_client() as test_client:
        yield test_client


@pytest.fixture(scope='session')
def token(client):
    rv = client.post('/api/auth/login', json={
        'username': 'admin',
        'password': '123456'
    })
    return rv.get_json()['data']['access_token']
